package com.liu;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * chance！Time
 *
 * @author liuqian
 * @date 2022-07-06 9:17
 * *
 */
public class UserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1,从数据库查询
        User user = findByUsername(username);
        //usernameGrantedAuthority:网络权限
        //建立一个集合
        //将角色放入authority网络权限中,在将该authority网络权限放入list中
        //然后将权限放入authority网络权限中,在将网络权限放入list中
        //这样list就有两个数据
        //一个角色,一个权限,区分就根据是否有ROLE_
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        list.add(authority);
        authority=new SimpleGrantedAuthority("add");
        list.add(authority);

        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
//        //2.2.将security需要登陆用户信息添加进org.springframework.security.core.userdetails.User，并返回
//        org.springframework.security.core.userdetails.User securityUser =
//                new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
//        return securityUser;
        return securityUser;
    }

    private User findByUsername(String username) {
        //假设从数据库查询到username和password
        //if("admin".equals(username)){
        //    User user = new User();
        //    user.setUsername("admin");
        //    user.setPassword("{noop}1234");
        //    return user;
        //}
        return null;
    }


//    测试BCryptPasswordEncode加密
    public static void main(String[]args){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    //   加密
    //    System.out.println(encoder.encode("1234"));
        System.out.println(encoder.matches("1234","$2a$10$zYJRscVUgHX1wqwu90WereuTmIg6h/JGirGG4SWBsZ60wVPCgtF8W"));
    }


}
